// 初始化端口基地址
axios.defaults.baseURL = 'https://hmajax.itheima.net'

// 初始化axios请求拦截器
axios.interceptors.request.use((config) => {
    const token = localStorage.getItem('token')
    if (token) config.headers.Authorization = token
    return config
}, err => { return Promise.reject(err) })

// 初始化axios响应拦截器
axios.interceptors.response.use(res => {
    return res
}, err => {
    console.log(err);
    if (err.response.status === 401) {
        showTost('登录失效请重新登录')
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        setTimeout(() => {
            location.href = './login.html'
        }, 1000)
    }
    if (err.response.status === 400) {
        showTost(err.response.data.message)
    }
    return Promise.reject(err)
})

// 封装公共吐司提示框
function showTost(message) {
    // 获取页面弹层的弹层模板
    const toast = document.querySelector('.toast')
    // 通过模板实例化一个弹层
    const registerToast = new bootstrap.Toast(toast)
    // 修改弹层内的提示文字
    toast.querySelector('.toast-body').innerText = message
    // 展示弹层
    registerToast.show()
    toast.style.zIndex = '5000'
}

// 封装登录鉴权
function checkLogin() {
    if (!localStorage.getItem('token')) {
        showTost('请先登录')
        setTimeout(() => {
            location.href = './login.html'
        }, 1000)
    }
}
// 封装退出登录
function logout() {
    document.querySelector('#logout').addEventListener('click', function () {
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        showTost('退出登录成功')
        setTimeout(() => {
            location.href = './login.html'
        }, 1000)
    })
}

// 更新用户名信息函数
function getname() {
    const username = localStorage.getItem('username')
    document.querySelector('.username').innerText = username
}